package com.andy.qhb.controller.game;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.andy.qhb.base.RespVO;
import com.andy.qhb.controller.GameController;
import com.andy.qhb.game.GameUtils;
import com.andy.qhb.game.GameConf;
import com.andy.qhb.game.GameUser;
import com.andy.qhb.game.Global;
import com.andy.qhb.game.QhbGame;
import com.andy.qhb.game.Room;
import com.andy.qhb.utils.GoConstant;
import com.andy.qhb.utils.JsonUtils;

@Controller
@RequestMapping(value="game/api")
public class Api121Controller extends GameController{
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	/**
	 * 发包
	 * @param session
	 * @param data
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="121")
	public RespVO action(HttpSession session,String data) throws Exception{
		GameUser user = getUser(session);
		Map<String, Object> reqData = JsonUtils.json2Map(data);
		Integer roomId = MapUtils.getInteger(reqData, "roomId");
		Integer coin = MapUtils.getInteger(reqData, "coin",0);
		Integer num = MapUtils.getInteger(reqData, "num",0);
		Integer lei = MapUtils.getInteger(reqData, "lei",0);
		
		Room room = Global.getRoom(roomId);
		if(room.getType() == GoConstant.GAME_TYPE_F) {
			return RespVO.createErrorJsonResonse("福利群不可以发红包");
		}
		
		if(coin <= 0 || num <= 0 || lei < 0) {
			return RespVO.createErrorJsonResonse("请输入完整信息");
		}
		if(lei > 999) {
			return RespVO.createErrorJsonResonse("最多只能三雷");
		}
		
		if(user.getGameInfo().getCoin() < coin) {
			return RespVO.createErrorJsonResonse("余额不足");
		}
		
		if(!checkFb(room,coin,num,lei)) {
			return RespVO.createErrorJsonResonse("输入不符合要求");
		}
		if(!room.isNorRoom()) {
			if(room.creater().getGameInfo().getCoin() < GameConf.groupCreateLimit*100) {
				return RespVO.createErrorJsonResonse("群主余额不足，请联系群主");
			}
		}
		
		QhbGame game = GameUtils.fab(user, coin, num, lei, room);
		
		return RespVO.createSuccessJsonResonse(game);
		
	}


	private boolean checkFb(Room room, Integer coin, int num, Integer lei) {
		if(room.getLow()*100 > coin || room.getHigh()*100 < coin) {
			return false;
		}
		if(room.getType() == GoConstant.GAME_TYPE_S && room.getNum() != num) {
			return false;
		}
		if(room.getType() == GoConstant.GAME_TYPE_J && (num != 5 && num != 6)) {
			return false;
		}
		if(room.getType() == GoConstant.GAME_TYPE_J && lei == 0) {
			return false;
		}
		return true;
	}
	
	
}